from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models.order import Order
from app.models.user import User
from app import db

orders_bp = Blueprint('orders', __name__)

@orders_bp.route('/orders', methods=['GET'])
@jwt_required()
def get_orders():
    # 获取当前用户ID
    user_id = get_jwt_identity()
    print('getOrders')
    # 获取查询参数
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    status = request.args.get('status')
    
    # 构建查询
    query = Order.query.filter_by(user_id=user_id)
    
    # 按状态筛选
    if status:
        query = query.filter(Order.status == status)
    
    # 分页
    pagination = query.order_by(Order.order_date.desc()).paginate(
        page=page, 
        per_page=per_page, 
        error_out=False
    )
    orders = pagination.items
    
    return jsonify({
        'orders': [{
            'id': order.id,
            'total_amount': order.total_amount,
            'order_date': order.order_date.isoformat(),
            'status': order.status,
            'shipping_address': order.shipping_address,
            'tracking_number': order.tracking_number,
            'payment_method': order.payment_method,
            'items': [{
                'id': item.id,
                'product_id': item.product_id,
                'quantity': item.quantity,
                'price': item.price,
                'product_name': item.product.name
            } for item in order.items]
        } for order in orders],
        'total': pagination.total,
        'pages': pagination.pages,
        'current_page': page
    }), 200

@orders_bp.route('/<int:order_id>/status', methods=['PUT'])
@jwt_required()
def update_order_status(order_id):
    # 获取当前用户ID
    user_id = get_jwt_identity()
    
    # 获取订单
    order = Order.query.filter_by(id=order_id, user_id=user_id).first_or_404()
    
    # 获取请求数据
    data = request.get_json()
    new_status = data.get('status')
    
    # 验证新状态
    if not new_status or new_status not in ['pending', 'paid', 'shipped', 'completed', 'cancelled']:
        return jsonify({'error': '无效的订单状态'}), 400
    
    # 检查用户权限
    user = User.query.get(user_id)
    if not user.is_admin() and new_status != 'cancelled':
        return jsonify({'error': '没有权限更新订单状态'}), 403
    
    # 更新订单状态
    order.status = new_status
    db.session.commit()
    
    return jsonify({
        'message': '订单状态更新成功',
        'order': {
            'id': order.id,
            'status': order.status
        }
    }), 200 